package com.chen.lifepic.downloader;

import java.util.HashSet;
import java.util.Vector;

import android.os.Environment;

import com.chen.lifepic.DataInfo.DataInfo;
import com.chen.lifepic.utils.APPCommonDef.PictureType;

public class DownloadManager implements ITaskListener {
	public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory()
			+ "/" + "LifePic" + "/";

	static DownloadManager _sManager = null;

	HashSet<IDownloadStatusListener> _listeners = null;

	AsyncTaskQueue _queue = null;

	Vector<BaseTask> _tasks = null;

	boolean _isThreadRun = false;

	protected DownloadManager() {
		_queue = new AsyncTaskQueue();
		_listeners = new HashSet<IDownloadStatusListener>();
	}

	public void destroy() {
		if (null != _queue) {
			_queue.destroy();
			_queue = null;
		}

		if (null != _listeners) {
			_listeners.clear();
			_listeners = null;
		}
	}

	public static DownloadManager getInstance() {
		if (null == _sManager)
			_sManager = new DownloadManager();
		return _sManager;
	}

	public static void releaseInstance() {
		_sManager.destroy();
		_sManager = null;
	}

	boolean downloaded = false;

	public void registerDownloadStatusListener(IDownloadStatusListener listener) {
		if (null == _listeners || null == listener)
			return;

		_listeners.add(listener);
	}

	public void unregisterDownloadStatusListener(
			IDownloadStatusListener listener) {
		if (null == _listeners || null == listener)
			return;
		_listeners.remove(listener);
	}

	public void addTaskToDownloadQueue(DataInfo info, PictureType type) {
		_queue.putToQueue(new HttpDownloadTask(info, this, type));
	}

	@Override
	public void TaskBegin() {
		if (null == _listeners)
			return;

		for (IDownloadStatusListener listener : _listeners) {
			if (null == listener)
				continue;

			listener.downloadBegin();
		}
	}

	@Override
	public void TaskFinish(BaseTask task) {
		if (null == _listeners)
			return;

		for (IDownloadStatusListener listener : _listeners) {
			if (null == listener)
				continue;

			listener.downloadFinish(task);
		}
	}

	@Override
	public void TaskProgress(long progress) {
		if (null == _listeners)
			return;

		for (IDownloadStatusListener listener : _listeners) {
			if (null == listener)
				continue;

			listener.downloadProgress(progress);
		}
	}

	Runnable downloadRunnable = new Runnable() {
		@Override
		public void run() {
			_isThreadRun = true;
			while (true) {
				try {
					if (null == _tasks || 0 == _tasks.size()) {
						_isThreadRun = false;
						return;
					}

					BaseTask task = _tasks.get(0);
					if (null == task) {
						Thread.sleep(100);
						continue;
					}

					task.start();
					_tasks.remove(task);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};
}
